package org.xxpay.pay.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.xxpay.apibase.constant.ABCS;
import org.xxpay.apibase.util.ZIPKit;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.exception.ServiceException;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.XXPayUtil;
import org.xxpay.core.entity.PayInterface;
import org.xxpay.core.entity.PayInterfaceType;
import org.xxpay.core.service.IXxPayIfstoreService;
import org.xxpay.pay.channel.PayConfig;
import org.xxpay.pay.service.CommonService;
import org.xxpay.pay.service.LocalDynamicChannelService;

import java.io.ByteArrayInputStream;
import java.util.List;

/** dubbo service,  向mgr提供接口微服务  **/
@Service(interfaceName = "org.xxpay.core.service.IXxPayIfstoreService", version = Constant.XXPAY_SERVICE_VERSION, retries = Constant.DUBBO_RETRIES)
public class XxPayIfstoreServiceImpl implements IXxPayIfstoreService {

    private static final MyLog _log = MyLog.getLog(XxPayIfstoreServiceImpl.class);

    @Autowired private LocalDynamicChannelService localDynamicChannelService;
    @Autowired private CommonService commonService;
    @Autowired private PayConfig payConfig;

    @Override
    @Transactional(transactionManager = "transactionManager", rollbackFor = Exception.class)
    public void overrideInstall(byte[] zipByteArrays) {

        String ifTypeCode = "未知";
        try {

            ZIPKit.checkFile(zipByteArrays, ABCS.IFSTORE_IFCHECK_PWD);

            String appJSONStr = ZIPKit.readFileText("app.json", "utf-8", new ByteArrayInputStream(zipByteArrays));

            JSONObject appJSON = JSONObject.parseObject(appJSONStr);

            ifTypeCode = appJSON.getString("ifTypeCode");

            PayInterfaceType dbPayInterfaceType = commonService.payInterfaceTypeService.findByCode(ifTypeCode); //当前数据库的配置

            //删除 通道
            commonService.payInterfaceTypeService.deletePayInterface(ifTypeCode);

            PayInterfaceType type = new PayInterfaceType();
            type.setIfTypeCode(ifTypeCode);
            type.setIfTypeName(appJSON.getString("ifTypeName"));
            type.setStatus(MchConstant.PUB_YES);
            type.setParam(appJSON.getJSONArray("param").toJSONString());
            type.setSupportConfigType(appJSON.getString("supportConfigType"));
            type.setIfSourceType(MchConstant.IF_SOURCE_TYPE_STORE_JAR);
            type.setIfVersion(appJSON.getString("ifVersion"));
            type.setRemark(appJSON.getString("remark"));

            if(dbPayInterfaceType != null){
                type.setMustFromTemplate(dbPayInterfaceType.getMustFromTemplate());    //通道子账号配置是否强制使用模板,0-否, 1-是
                type.setWhiteIp(dbPayInterfaceType.getWhiteIp()); //回调IP白名单,半角逗号分隔
                type.setOrderExpire(dbPayInterfaceType.getOrderExpire());  //订单超时时间，默认分钟
                type.setPayConfirmAmount(dbPayInterfaceType.getPayConfirmAmount());     //支付确认金额单位分,默认为-1不限制
                type.setEnableNotify(dbPayInterfaceType.getEnableNotify()); // 是否允许回调
            }

            commonService.payInterfaceTypeService.add(type);

            //通道接口
            List<PayInterface> interfaceList = JSONArray.parseArray(appJSON.getString("payInterfaceArray"), PayInterface.class);
            for (PayInterface item : interfaceList) {
                item.setIfTypeCode(ifTypeCode);
                item.setStatus(MchConstant.PUB_YES);
                commonService.payInterfaceService.add(item);
            }

            //文件保存到指定目录
            String saveJarPath = XXPayUtil.getJarPath(ifTypeCode, payConfig.getIfStoreLocalLoadjarPath());

            //保存文件
            ZIPKit.unzipInnerFile(new ByteArrayInputStream(zipByteArrays), "app.jar", saveJarPath);

            //重新加载动态通道
            localDynamicChannelService.reloadJar(ifTypeCode);

        } catch (Exception e) {
            _log.error("安装动态通道 [{}]失败！", ifTypeCode, e);
            throw new ServiceException(RetEnum.RET_COMM_OPERATION_FAIL);
        }
    }
}
